<?php

class Admin_AuthController extends Admin_Library_Controller_Action
{

    /**
     * @todo redirect to login page
     * @return void
     */
    public function indexAction()
    {
        $urlOptions = array(
            'module' => 'admin',
            'controller' => 'auth',
            'action' => 'login'
        );
        $this->_helper->redirector->gotoRoute($urlOptions);
    }

    /**
     * @todo Authentication
     * valid: redirect to default administrator site.
     * invalid: alert error message.
     *
     * @return void
     */
    public function loginAction()
    {
        // redirect to admin panel if user loged-in
        if (!empty($this->view->userProfile)) {
            $urlOptions = array(
                'module' => 'admin',
                'controller' => 'index',
                'action' => 'index'
            );
            $this->_helper->redirector->gotoRoute($urlOptions);
        }

        // Start
        // 1.   set layout to admin_login.phtml
        $this->_helper->layout->setLayout('login');
        $request = $this->getRequest();

        // 2. Render form
        $form = new Admin_Form_Login();

        // 3. submit form
        if ($request->isPost() && $form->isValid($request->getPost())) {
            $values = array();
            $values['username'] = $request->getParam('username');
            $encrypted = $request->getParam('password');
            $decrypted = base64_decode($encrypted);
            $values['password'] = str_replace($this->view->config->salt, '', $decrypted);
            // 2.2  login process
            if ($this->process($values)) {
                $urlOptions = array(
                    'module' => 'admin',
                    'controller' => 'index',
                    'action' => 'index'
                );
                $this->_helper->redirector->gotoRoute($urlOptions);
            } else {
                $this->view->msg = 'username-or-password-not-match';
            }
        }
		
        $this->view->headScript()->appendFile($this->view->themePath . '/js/jquery.base64.min.js', 'text/javascript');
        $this->view->headScript()->appendFile($this->view->themePath . '/js/admin-auth.js', 'text/javascript');
        $this->view->form = $form;
    }

    /**
     * @todo clear authenticated session
     * @return void
     */
    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        if(isset($_SESSION['KCFINDER'])) {
            unset($_SESSION['KCFINDER']);
        }
        $urlOptions = array(
            'module' => 'admin',
            'controller' => 'auth',
            'action' => 'login'
        );
        $this->_helper->redirector->gotoRoute($urlOptions);
        /*
          $auth = Zend_Auth::getInstance();
          $storage = new APPCore_Auth_Storage_Db(new Model_StorageSession());
          $auth->setStorage($storage);
          $auth->clearIdentity();
          $urlOptions = array('module' => 'admin', 'controller' => 'auth', 'action' => 'login');
          $this->_helper->redirector->gotoRoute($urlOptions); */
    }
    
    /**
     * @todo get Salt
     * @return void
     */
    public function getSaltAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);
    	$data = array();
    	$data['salt'] = $this->view->config->salt;
    	echo json_encode($data);
    	exit;
    }

    /**
     * @todo Login process
     * @param Array $values
     * @return boolean
     */
    private function process($values)
    {
        $result = false;
        $modelUser = new Model_User();
        $check = $modelUser->userLogin($values);
        if ($check) {
            $check['is_admin'] = $modelUser->isAdmin($check['id']);
            $userRole = $modelUser->getRoleUser($check['id']);
            $role_name = 'Guest';
            $role_id = 5;
            if(isset($userRole ['role_name']) && isset($userRole ['role_id'])) {
                $role_name = $userRole ['role_name'];
                $check['role_name'] = $role_name;
                $check['role_id'] = $userRole ['role_id'];
            }
            $resourceObj = new Model_Entities_AclResource();
            $wheres = array('status = 1');
            if($check['role_id'] == 1) {
                $wheres = array();
            }
            $check['resources'] = $resourceObj->getArray(0, 0, $wheres, array('id'));
            Zend_Auth::getInstance()->getStorage('BO')->write($check);
            $result = true;
        }
        return $result;
    }
}